package net.lab1024.sa.admin.module.open.result;

import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.device.terminal.DeviceTerminalService;
import net.lab1024.sa.admin.module.device.terminal.domain.DeviceTerminalEntity;
import net.lab1024.sa.admin.module.open.result.constants.ResultConstant;
import net.lab1024.sa.admin.module.open.result.domain.ResultInfoForm;
import net.lab1024.sa.admin.module.upstream.box.UpstreamBoxService;
import net.lab1024.sa.base.common.enumeration.ExecuteStatusEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Slf4j
@Service
public class ExecuteResultService {

    private final DeviceTerminalService deviceTerminalService;

    private final UpstreamBoxService upstreamBoxService;

    public ExecuteResultService(DeviceTerminalService deviceTerminalService,
                                UpstreamBoxService upstreamBoxService) {
        this.deviceTerminalService = deviceTerminalService;
        this.upstreamBoxService = upstreamBoxService;
    }

    @Transactional(rollbackFor = Exception.class)
    public void deployResult(ResultInfoForm form) {
        // 根据设备序列号查询
        DeviceTerminalEntity deviceTerminalEntity = deviceTerminalService.getBySerialno(form.getSerialno());
        if (deviceTerminalEntity == null) {
            log.error("终端设备不存在，设备序列号：{}", form.getSerialno());
            return;
        }
        // 上报的参数值赋值到实体

        deviceTerminalEntity.setExecuteResult(form.getExecuteResult());
        Boolean state = Optional.ofNullable(form.getExecuteState()).orElse(false);
        Integer executeStatus =
                state ? ExecuteStatusEnum.SUCCESS.getValue() : ExecuteStatusEnum.FAIL.getValue();
        deviceTerminalEntity.setExecuteStatus(executeStatus);
        if (!ResultConstant.DEFAULT.equals(form.getUpstreamId())) {
            deviceTerminalEntity.setUpstreamId(form.getUpstreamId());
            deviceTerminalEntity.setUpstreamCode(form.getUpstreamCode());
            // 保存上游节点信息
            upstreamBoxService.saveByDeployResult(deviceTerminalEntity);
        }
        // 上报结果更新到设备终端信息
        deviceTerminalService.update(deviceTerminalEntity);
    }
}
